package com.asen.libcommon.http.interceptor

import com.asen.libcommon.base.BaseApplication
import com.asen.libcommon.util.NetWorkUtil
import okhttp3.CacheControl
import okhttp3.Interceptor
import okhttp3.Response

/**
 * @date   : 2021/1/18
 * @author : asenLiang
 * @e-mail : liangAisiSen@163.com
 * @desc   : 缓存拦截器
 */

class CacheInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {

        val request = chain.request()

        return when (NetWorkUtil.isConnected(BaseApplication.application)) {

            true ->   // 有网络不缓存
                chain
                    .proceed(request).newBuilder()
                    .header("Cache-Control", "public, max-age=${0}")
                    .removeHeader("Retrofit")// 清除头信息，因为服务器如果不支持，会返回一些干扰信息，不清除下面无法生效
                    .build()

            false -> { // 无网络缓存一周
                chain
                    .proceed(request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build())
                    .newBuilder()
                    .header(
                        "Cache-Control",
                        "public, only-if-cached, max-stale=${60 * 60 * 24 * 28}"
                    )
                    .removeHeader("nyn")
                    .build()
            }

        }

    }

}